#!/bin/bash
#===============================================================================
#
#          FILE:  deploy.sh
#
#
#   DESCRIPTION:  script to build and deploy local console
#
#       OPTIONS:  ---
#  REQUIREMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR:  LONG KAI MAO
#       VERSION:  1.0
#       CREATED:  10/14/2022 11:03:36 AM CST
#      REVISION:  ---
#===============================================================================#
SCRIPT=$(readlink -f "$0")
SCRIPT_PATH=$(dirname "${SCRIPT}")

command=$1
MAVEN_PATH=`which mvn`
export PATH=$PATH:${MAVEN_PATH}/bin/
DINGTALK_URL="https://oapi.dingtalk.com/robot/send?access_token=${DINGTALK_CREDS}"

TEMPLATE_SOURCE_SUFFIX=".template"
TEMPLATE_SOURCE_DIR="${WORKSPACE}/local/web/tengine/conf/includes/tpl"
TARGET_DIR="${WORKSPACE}/target"
HTML_TARGET_DIR="${TARGET_DIR}/html"
CONF_TARGET_DIR="${TARGET_DIR}/conf"
CONF_INCLUDES_TARGET_DIR="${CONF_TARGET_DIR}/includes"

RANCHER_TEMPLATE_DIR="${WORKSPACE}/local/web/rancher/tpl"



function usage() {
    echo "USAGE: ${SCRIPT} [-h]"
    echo -e "\t -h to show usage"
    echo -e "\t -c to clean firstly"
    exit 0
}

# shellcheck disable=SC2068
function buildCode() {
    echo "begin buildCode ..."
    echo "nodejs version:"
    node -v
    echo "npm version:"
    npm -v

    local old_ifs="$IFS"
    IFS=","
    local APP_NAME_ARR=($APP_NAME)
    IFS="$old_ifs"

    rm -rf "${TARGET_DIR}"

    if [ ! -d "${TARGET_DIR}" ]; then
        mkdir -p "${TARGET_DIR}"
    fi

    if [ ! -d "${HTML_TARGET_DIR}/${HTML_CONSOLE}" ]; then
        mkdir -p "${HTML_TARGET_DIR}/${HTML_CONSOLE}"
    fi

    for app in ${APP_NAME_ARR[@]}
      do (
         echo "build $app begin ..."

         cd "${WORKSPACE}/${app}"
         gitLog=$(git rev-parse --short HEAD)
         echo "${app}：${gitLog}" >> "${HTML_TARGET_DIR}/${HTML_CONSOLE}/gitlog.file"
         npm i

         case "${app}" in
              "console")
                  npm run build:front
                  cp -r dist/* "${HTML_TARGET_DIR}/${HTML_CONSOLE}"
                  ;;

              "operation")
                  npm run build:front
                  cp -r dist "${HTML_TARGET_DIR}/${HTML_CONSOLE}/operation"
                  ;;

              "realNameMountApp")
                  npm run build
                  cp -r dist "${HTML_TARGET_DIR}/${HTML_CONSOLE}/realNameMountApp"
                  ;;

              "signMountApp")
                  npm run build:front
                  cp -r dist "${HTML_TARGET_DIR}/${HTML_CONSOLE}/signMountApp"
                  ;;
         esac;
      )&

      done
      wait

    handlerConf

}

function handlerConf() {
    echo 'begin handler nginx config ...'

    local template defined_envs relative_path output_path

    mkdir -p "${CONF_INCLUDES_TARGET_DIR}"
    cp "${WORKSPACE}/local/web/tengine/conf/nginx.conf" "${CONF_TARGET_DIR}/nginx.conf"

    defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))
    [ -d "${TEMPLATE_SOURCE_DIR}" ] || return 0
    if [ ! -w "${CONF_TARGET_DIR}" ]; then
        echo >&3 "$ME: ERROR: ${TEMPLATE_SOURCE_DIR} exists, but ${CONF_TARGET_DIR} is not writable"
        return 0
    fi

    find "${TEMPLATE_SOURCE_DIR}" -follow -type f -name "*${TEMPLATE_SOURCE_SUFFIX}" -print | while read -r template; do
        relative_path="${template#${TEMPLATE_SOURCE_DIR}/}"
        output_path="${CONF_INCLUDES_TARGET_DIR}/${relative_path%${TEMPLATE_SOURCE_SUFFIX}}"
        envsubst "$defined_envs" <"$template" >"${output_path}.conf"
    done
}

function buildImage() {
    echo "buildImage begin ..."
    docker login -u tianweiyun_kaifa -p aliyunKAIFA2019 https://harbor-tw.itrus.com.cn
    docker build "${TARGET_DIR}" -t "${IMAGE_NAME}" -f "${WORKSPACE}/local/web/dockerfile/Dockerfile"
}

function pushImage() {
    echo "pushImage begin ..."
    docker push "${IMAGE_NAME}"
    docker rmi "${IMAGE_NAME}"
    docker logout
}


function deployToRancher() {
    echo "create rancher and deploy to rancher begin ..."
    local defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))
    mkdir -p ${RANCHER_TARGET_DIR}
    envsubst "$defined_envs" <"${RANCHER_TEMPLATE_DIR}/deploy.json" >"${RANCHER_TARGET_DIR}/deploy.json"
    local body=$(cat "${RANCHER_TARGET_DIR}/deploy.json")
    echo ${body}

    curl -k -u "${RANCHER_TOKEN}" \
            -X POST \
            -H 'Accept: application/json' \
            -H 'Content-Type: application/json' \
            -d "${body}" \
            "${RANCHER_WORKLOAD}"
}

function reDeployToRancher() {
    echo "re deploy begin ..."
    local project_api_url="$RANCHER_WORKLOAD"/deployment:"$RANCHER_NAMESPACE":"$PROJECT_NAME";

    curl -k -u "${RANCHER_TOKEN}" \
          -X PUT \
          -H 'Accept: application/json' \
          -H 'Content-Type: application/json' \
          -d '
            {
                "containers":[
                    {
                        "image":"'"${IMAGE_NAME}"'",
                        "name":"'"${PROJECT_NAME}"'"
                    }
                ]
            }
          ' \
          "${project_api_url}"
}


# shellcheck disable=SC2206
# shellcheck disable=SC2068
function createRancherNamespace() {
  echo "create rancher namespace begin ..."

  local old_ifs="$IFS"
  IFS="/"
  local arr=($RANCHER_WORKLOAD)

  IFS=":"
  local projectArr=(${arr[5]})
  IFS="$old_ifs"

  local clusterId=${projectArr[0]}
  local projectId=${arr[5]}
  local rancher_namespace_api="${arr[0]}//${arr[2]}/${arr[3]}/clusters/${projectArr[0]}/namespace"

  curl -k -u "${RANCHER_TOKEN}" \
      -X POST \
      -H 'Accept: application/json' \
      -H 'Content-Type: application/json' \
      -d '{"type":"namespace","name":"'"${RANCHER_NAMESPACE}"'","clusterId":"'"${clusterId}"'","projectId":"'"${projectId}"'","resourceQuota":null,"labels":{}}' \
      "${rancher_namespace_api}"

}

#=====================================================
# 1、如果开启了初始化Rancher和nacos，则
#     （1）、创建Nacos命名空间
#     （2）、生成Nacos配置文件，并上传到Nacos中
#     （3）、创建Rancher命名空间
#     （4）、全新部署到Rancher中
# 2、如果没有开启，则重新部署到指定的Rancher中。
#====================================================#
# shellcheck disable=SC2016
function pubRancher() {
    echo "pubRancher begin ..."

    if ${INIT_RANCHER_NACOS};  then
        createRancherNamespace
        deployToRancher

    else
        reDeployToRancher
    fi
}


# shellcheck disable=SC2016
function sucNotify() {
   echo "sucNotify begin ..."
   local req_body="😄👍 构建成功 👍😄  \n**项目名称**：${PROJECT_NAME}  \n**镜像地址**: ${IMAGE_NAME}   \n**构建地址**：${RUN_DISPLAY_URL}  \n**测试报告地址**：${AUTO_TEST_URL}    \n**构建任务**：${BUILD_TASKS}"
   curl "${DINGTALK_URL}" \
       -H 'Content-Type: application/json' \
       -d '{
           "msgtype": "markdown",
           "markdown": {
               "title":"'"${PROJECT_NAME}"'",
               "text": "'"${req_body}"'"
           }
       }'
}

function failNotify() {
   echo "failNotify begin ..."
   local req_body="😖❌ 构建失败 ❌😖  \n**项目名称**：${PROJECT_NAME}   \n**镜像地址**: ${IMAGE_NAME}   \n**构建地址**：${RUN_DISPLAY_URL}  \n**测试报告地址**：${AUTO_TEST_URL}    \n**构建任务**：${BUILD_TASKS}"
   curl "${DINGTALK_URL}" \
       -H 'Content-Type: application/json' \
       -d '{
           "msgtype": "markdown",
           "markdown": {
               "title":"'"${PROJECT_NAME}"'",
               "text": "'"${req_body}"'"
           }
       }'
}

case $command in
    (b)
       buildCode
       ;;
    (i)
       buildImage
       ;;
    (pi)
       pushImage
       ;;
    (p)
       pubRancher
       ;;
    (sn)
       sucNotify
       ;;
    (fn)
       failNotify
       ;;

    (*)
       echo "Error command"
       echo "$usage"
       ;;
esac